package com.vecspace.datacenter.dataprocess.service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import com.vecspace.database.model.ConnectionParam;
import com.vecspace.statistics.counter.Stopwatch;
import com.vecspace.utils.log.HLogger;

/**用户进行数据处理。比如将基础数据进行统计分析，将结果数据存入结果表中。
 *  
 * @类型名称: DbDataProcess
 * @version: 1.0
 * @author: wanghua
 */
public abstract class DbDataProcess extends DataProcess{
	@Override
	public boolean execute(String args) {
		Connection conn = null;		
		try{
			conn = this.getConnection();
			Stopwatch newStopwatch = stopwatcher.newStopwatch();
			boolean result = doDataProcess(conn, args);
			newStopwatch.startTicking();
			return result;
		}catch(Exception ex){
			HLogger.DEFAULT().error(ex);
			return false;
		}
		finally{
			try {
				if(conn != null){
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}		
	}
	
	/**操作数据库
	 * 建议使用DbUtils工具类进行数据库操作。
	 * @param conn 数据库连接（使用完后不需要close）
	 * @throws Exception 
	 * @author: wanghua
	 */
	public abstract boolean doDataProcess(Connection conn, String args) throws Exception;
	
	/**
	 * 
	 * 功能描述：
	 * @return
	 * @throws Exception 
	 * @author: wanghua
	 */
	protected Connection getConnection() throws Exception{
		ConnectionParam connparam = connParam;
		Class.forName(connparam.getDriverClassName());
		Connection conn = DriverManager.getConnection(connparam.getUrl(),connparam.getUserId(),connparam.getPassword());
		return conn;
	}
	
	/**
	 * @param connparam
	 * @return
	 * @throws Exception 
	 * @author: wanghua
	 */
	protected Connection getConnection(ConnectionParam connparam) throws Exception{
		if(connparam == null)return null;
		Class.forName(connparam.getDriverClassName());
		Connection conn = DriverManager.getConnection(connparam.getUrl(),connparam.getUserId(),connparam.getPassword());
		return conn;
	}
	
	private ConnectionParam connParam;
	
	public ConnectionParam getConnParam() {
		return connParam;
	}

	public void setConnParam(ConnectionParam connParam) {
		this.connParam = connParam;
	}
}
